package server;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.mapper.Context;
import server.mapper.Host;
import server.mapper.Mapper;
import server.mapper.Wrapper;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class HomeworkBootstrap {

    public static void main(String[] args) throws Exception {
        new HomeworkBootstrap().start();
    }


    public void start() throws Exception {
        Mapper mapper = loadMapper();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        for (String name : mapper.getHostMap().keySet()) {
            threadPoolExecutor.submit(() -> {
                Host host = mapper.get(name);
                try (ServerSocket ss = new ServerSocket(Integer.parseInt(host.getPort()))) {
                    for (; ; ) {
                        Socket socket = ss.accept();
                        HomeworkRequestProcessor requestProcessor = new HomeworkRequestProcessor(socket, mapper);
                        threadPoolExecutor.execute(requestProcessor);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }

        new CountDownLatch(1).await();

    }

    private Mapper loadMapper() {
        Mapper mapper = new Mapper();

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> eleServiceList = rootElement.selectNodes("//Service");
            for (Element eleService : eleServiceList) {
                Element eleConnector = (Element) eleService.selectSingleNode("Connector");
                String port = eleConnector.attributeValue("port");

                Element eleHost = (Element) eleService.selectSingleNode("Host");
                Host host = loadHost(port, eleHost);
                if (host == null) {
                    continue;
                }
                mapper.put(port, host);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapper;
    }

    private Host loadHost(String port, Element eleHost) throws FileNotFoundException {

        // 获取目录
        String appBase = eleHost.attributeValue("appBase");
        // 判断是否有此目录和web.xml文件
        File appBaseFile = new File(appBase);
        File[] appFile = appBaseFile.listFiles();
        if (appFile == null) {
            return null;
        }

        Map<String, Context> urlContextMap = new HashMap<>();
        for (File file : appFile) {
            // 配置文件
            File webConfigFile = new File(file + "/web.xml");
            if (!webConfigFile.exists()) {
                continue;
            }

            // 加载 web.xml
            Context context = loadServlet(file, webConfigFile);

            // 载入到 host 中
            urlContextMap.put(file.getName(), context);
        }

        String name = eleHost.attributeValue("name");
        return new Host(name, port, urlContextMap);
    }

    /**
     * 加载解析web.xml，初始化Servlet
     *
     * @return
     */
    private Context loadServlet(File dir, File file) throws FileNotFoundException {
        InputStream resourceAsStream = new FileInputStream(file);
        SAXReader saxReader = new SAXReader();

        Map<String, Wrapper> wrapperMap = new HashMap<>();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                String clazzFile = dir.getAbsolutePath() + "/" + servletClass.replaceAll("\\.", "/") + ".class";
                // 加载 appBase 目录下的servlet
                Class<?> aClass = new MyClassLoader().findClass(clazzFile);
                HttpServlet httpServlet = (HttpServlet) aClass.newInstance();
                wrapperMap.put(urlPattern, new Wrapper(servletName, httpServlet));
            }
        } catch (DocumentException | IllegalAccessException | InstantiationException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return new Context(dir.getAbsolutePath(), wrapperMap);
    }


}
